<template>
  <a-modal :width="700" v-model:visible="showPortfolioDialog" :title="currentData.id ? '编辑组合' : '添加组合'" title-align="start" :mask-closable="false" :on-before-ok="submitData" :ok-loading="submitLoading" @cancel="closedDialog">
    <a-form style="width: 500px" ref="formRef" :model="formInfo" :rules="rulesUser">
      <a-form-item field="shopId" label="选择店铺">
        <a-select v-model="market" :disabled="currentData.id ? true : false" value-key="marketplaceId" allow-search style="width: 150px" @change="getFilterShop">
          <a-option v-for="(markedt, i) in markedtList" :key="i" :value="markedt" :label="`${markedt.marketplaceName}(${markedt.marketplaceCode})`" />
        </a-select>
        <a-select v-model="formInfo.shopId" :disabled="currentData.id ? true : false" placeholder="请选择" allow-search allow-clear>
          <a-option v-for="(shop, i) in filterShopList" :key="i" :value="shop.id" :label="shop.shopName" />
        </a-select>
      </a-form-item>
      <a-form-item label="组合ID" v-if="currentData.id">
        <p>{{ formInfo.portfolioId }}</p>
      </a-form-item>
      <a-form-item field="portfoliosName" label="组合名称">
        <a-input v-model="formInfo.portfoliosName" placeholder="请输入" allow-clear />
      </a-form-item>
      <a-form-item field="ownerId" label="销售员">
        <a-select v-model="formInfo.ownerId" placeholder="请选择" allow-search allow-clear>
          <a-option v-for="(user, i) in userList" :key="i" :value="user.id" :label="user.userName" />
        </a-select>
      </a-form-item>
      <a-form-item label="预算上限">
        <a-select v-model="formInfo.budgetType" style="width: 140px">
          <a-option value="noBudgetCap" label="预算无上限" />
          <a-option value="dateRange" label="按日期范围" />
          <a-option value="monthlyRecurring" label="按月定期" />
        </a-select>
        <template v-if="formInfo.budgetType != 'noBudgetCap'">
          <a-input-number style="margin: 0 10px" v-model="formInfo.budget" placeholder="必填" />
          <p>{{ market.currency }}</p>
        </template>
      </a-form-item>
      <a-form-item v-if="formInfo.budgetType == 'monthlyRecurring'" label="结束日期">
        <a-date-picker v-model="formInfo.budgetEndDate" style="width: 200px" placeholder="无结束日期" />
      </a-form-item>
      <a-form-item v-if="formInfo.budgetType == 'dateRange'" label="日期范围">
        <a-date-picker v-model="formInfo.budgetStartDate" style="width: 200px" />
        <span>-</span>
        <a-date-picker v-model="formInfo.budgetEndDate" style="width: 200px" placeholder="无结束日期" />
      </a-form-item>
    </a-form>
    <a-alert v-if="formInfo.budgetType != 'noBudgetCap'">
      <p v-if="formInfo.budgetType == 'dateRange'">
        <span>预算上限：USD {{ formInfo.budget }}总支出，</span>
        <span>从{{ $setTime(formInfo.budgetStartDate, 'YYYY年MM月DD日') }}开始，</span>
        <span v-if="formInfo.budgetEndDate">于{{ $setTime(formInfo.budgetEndDate, 'YYYY年MM月DD日') }}结束</span>
      </p>
      <p v-if="formInfo.budgetType == 'monthlyRecurring'">
        <span>预算上限：{{ market.currency }} {{ formInfo.budget }}每月，</span>
        <span>每月1日重新启动，</span>
        <span v-if="formInfo.budgetEndDate">于{{ $setTime(formInfo.budgetEndDate, 'YYYY年MM月DD日') }}结束</span>
      </p>
    </a-alert>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, PropType, onMounted } from 'vue'
  import { addpPortfolios } from '@/api/advert'
  import { Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  onMounted(async () => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    markedtList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    userList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  })
  const rulesUser = ref({
    shopId: [{ required: true, message: '请选择店铺' }],
    portfoliosName: [{ required: true, message: '请输入组合名称' }],
    ownerId: [{ required: true, message: '请选择销售员' }],
    budget: [{ required: true, message: '请输入预算金额' }],
  })

  const showPortfolioDialog = ref(props.isShow)
  const formInfo = ref<any>({
    budgetType: 'noBudgetCap',
    budgetStartDate: dayjs().startOf('day').format('YYYY-MM-DD'),
  })
  const market = ref()
  const formRef = ref()
  const submitLoading = ref(false)
  const filterShopList = ref<Array<any>>([])

  function setDefaultData() {
    if (props.currentData.id) {
      market.value = props.markedtList.find((el) => el.marketplaceId == props.currentData.marketplaceId) || {}
      formInfo.value.portfoliosName = props.currentData.portfolioName
      formInfo.value.shopId = props.currentData.shopId
      formInfo.value.ownerId = props.currentData.ownerId
      formInfo.value.budgetType = props.currentData.budgetPolicy || 'noBudgetCap'
      formInfo.value.budgetStartDate = props.currentData.budgetAmountStartDate || dayjs().startOf('day').format('YYYY-MM-DD')
      formInfo.value.budgetEndDate = props.currentData.budgetAmountEndDate
      formInfo.value.budget = props.currentData.budgetAmount
      formInfo.value.portfolioId = props.currentData.portfolioId
    } else {
      market.value = {
        marketplaceId: 'ATVPDKIKX0DER',
        currency: 'USD',
      }
    }
    getFilterShop()
  }
  // 过滤店铺
  function getFilterShop() {
    filterShopList.value = props.shopList.filter((el: any) => el.marketplaceId === market.value.marketplaceId)
    if (!filterShopList.value.find((el: any) => el.id === formInfo.value.shopId)) formInfo.value.shopId = null
  }
  // 关闭
  function closedDialog() {
    formInfo.value = {}
    formRef.value.clearValidate()
    showPortfolioDialog.value = false
    emit('closed')
  }
  // 提交组合信息
  async function submitData() {
    let valid = await formRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let params = JSON.parse(JSON.stringify(formInfo.value))
    if (params.budgetType == 'noBudgetCap') {
      delete params.budget
      delete params.budgetStartDate
      delete params.budgetEndDate
    } else if (params.budgetType == 'monthlyRecurring') {
      delete params.budgetStartDate
    }
    if (params.budgetType != 'noBudgetCap' && !params.budget) {
      Message.error('预算金额必填')
      return false
    }
    const res: any = await addpPortfolios(params)
    if (res) {
      Message.success('创建组合成功')
      emit('success')
      emit('closed')
      return true
    }
    return false
  }
</script>
<style lang="less" scoped>
  .info-text {
    padding-left: 20px;
    font-size: 12px;
    color: #999;
    .title {
      margin-bottom: 10px;
    }
  }
  .arco-alert {
    background-color: rgb(232, 243, 255);
    font-size: 12px;
  }
</style>
